import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        version: "1.0",
        token: null, //身份认证token
        user: {
            uid: 0,
            name: '',
            avatar: '',
            mobile: '',
        },
        layout: "default",
    },
    mutations: {
        user: function (state, user) {
            state.user = user;
            if (user === null) {
                state.user = {
                    uid: 0,
                    name: '',
                    avatar: '',
                    mobile: '',
                };

                localStorage.removeItem("user");
            } else {
                user.avatar = user.avatar === null ? '' : user.avatar;
                localStorage.setItem("user", JSON.stringify(user));
            }
        },
        token(state, token) {
            state.token = token;
            if (token === null) {
                localStorage.removeItem("token");
            } else {
                localStorage.setItem("token", JSON.stringify(token));
            }
        },
        layout(state, layout) {
            state.layout = layout;
        },
    },
    actions: {
        user(context, user) {
            context.commit("user", user);
        },
        token(context, token) {
            context.commit("token", token);
        },
        layout(context, layout) {
            context.commit("layout", layout);
        },
    },
    getters: {
        uid: state => {
            let uid = 0;
            // 如果没有数据则检查本地存储
            if (state.user.uid) {
                uid = state.user.uid;
            } else {
                let obj = JSON.parse(localStorage.getItem("user"));
                if (obj === null) {
                    return 0;
                } else {
                    state.user = obj;
                    uid = state.user.uid;
                }
            }
            return isNaN(parseInt(uid)) ? 0 : parseInt(uid);
        },
        user: state => {
            // 如果没有数据则检查本地存储
            if (state.user.uid) {
                return state.user;
            } else {
                let obj = JSON.parse(localStorage.getItem("user"));
                if (obj === null) {
                    return state.user;
                } else {
                    state.user = obj;
                    return state.user;
                }
            }
        },
        token: state => {
            // 如果没有数据则检查本地存储
            if (state.token) {
                return state.token;
            } else {
                let obj = JSON.parse(localStorage.getItem("token"));
                if (obj !== null) {
                    state.token = obj;
                    return state.token;
                }
            }
        },
        layout: state => state.layout,
    }
});
export default store;
